package folderLogger;

import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;

public class CoverImageMod {

	public enum ImageReferenceType
	{
		ABSOLUTE_PATH,
		COPY,
		NONE
	}
	
	private int imageCounter;
	private String outputFolder;
	private String imagesFolder;
	
	private boolean isActive;
	
	public CoverImageMod(String outputFolder, String imagesFolder)
	{
		this.outputFolder = outputFolder;
		this.imagesFolder = imagesFolder;
		imageCounter = 0;
		isActive = true;
	}
	
	public void setActiveMode(boolean isActive)
	{
		this.isActive = isActive;
	}
	
	public String RenameImage(String imageFileName, ImageReferenceType isCopyImages) {
		switch(isCopyImages)
		{
		case ABSOLUTE_PATH:
			return imageFileName;
		case COPY:
			if(imageFileName == "")
			{
				return imageFileName;
			}
			
			String relativePath = String.format("%s\\%s.%s", imagesFolder, String.valueOf(imageCounter++), "jpg");
			String newName = String.format("%s\\%s",outputFolder, relativePath);
			
			if(isActive)
			{			
				//	Begin copy:
				File dir = new File(String.format("%s\\%s", outputFolder, imagesFolder));
				if(!dir.exists() || !dir.isDirectory())
				{
					dir.mkdir();
				}
				File originalFile = new File(imageFileName);
				if(!originalFile.exists())
				{
					return "";
				}
	
				File newFile = new File(newName);
				try {
					newFile.createNewFile();
				} catch (IOException e) {
					return "";
				}
				//	copy the file to new location 
				try {
					Files.copy(originalFile.toPath(), newFile.toPath(),
							StandardCopyOption.REPLACE_EXISTING);
				} catch (IOException e) {
					newFile.delete();
					return "";
				}
			}
			return relativePath;
		case NONE:
			return "";
		default:
			return null;
		
		}
	}

	public static String FindImageFile(File currentFolder) {
		File[] matchingFiles = currentFolder.listFiles(new FilenameFilter() {
		    public boolean accept(File dir, String name) {
		        return name.equalsIgnoreCase("folder.jpg");
		    }
		});
		return (matchingFiles.length > 0) ? matchingFiles[0].getAbsolutePath() : "";
	}
	
}
